package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.LoanFlowMqConstant;
import com.niiwoo.civet.trade.service.local.auth.AuthService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author wping
 * @Description: 授权数据获取状态检查MQ监听器
 * @date 2018/4/20 10:09
 */
@Slf4j
@Component
public class AuthStatusCheckListener {

    @Autowired
    private AuthService authService;

    @RabbitListener(queues = {LoanFlowMqConstant.Queue.AUTH_STATUS_CHECK_QUEUE})
    public void onMessage(Message message, Channel channel) {
        log.info("授权数据获取状态检查MQ, 请求报文:{}", message.getBody());
        Long flowExecuteId = null;
        try {
            String reqMsg = new String(message.getBody(), Charset.forName("UTF-8"));
            flowExecuteId = JSON.parseObject(reqMsg).getLong("flowExecuteId");
            authService.executeAuthStatusCheck(flowExecuteId);
        } catch (Exception e) {
            log.error("授权数据获取状态检查MQ-处理异常, flowExecuteId:{}", flowExecuteId, e);
        } finally {
            doAckAnwser(message, channel);
        }
    }

    private void doAckAnwser(Message message, Channel channel) {
        try {
            //确认消息已经接收;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException ie) {
            log.error("授权数据获取状态检查MQ-ACK异常, 异常原因:{}", ie);
        }
    }

}
